package com.dyrnq.seckill.interceptor;

import com.dyrnq.seckill.dto.UserDTO;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class GlobalInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 在请求处理之前设置全局变量到 Model 中
        HttpSession session = request.getSession(false);
        Object userDTO =null;
        if(session!=null){
            userDTO = session.getAttribute("user");
        }
        // 将session中的user对象拿出来放到request中（如果session中有的话，此处不主动创建session）
        // 此功能需要使用共享session，比如redis session
        request.setAttribute("user", userDTO);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 在请求处理之后可以做一些处理
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求完成后可以做一些清理工作
    }
}
